package library;

/***
 * @author Ragnvald Fuglestein
 */

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import localFiles.LocalTrackAddon;

import baseStructure.Addon;
import baseStructure.ExtendedSearch;
import baseStructure.Track;

public class PlayList {
	private List<PlayListTrack> tracks = new ArrayList<>();
	private String name;
	
	public PlayList(String name) {
		this.name = name;
	}
	
	public class PlayListTrack {
		List<Track> tracks = new ArrayList<>();
		
		public PlayListTrack(Track track) {
			this.tracks.add(track);
		}
		
		public void add(Track track) {
			if (!tracks.contains(track)) this.tracks.add(track);
		}
		
		public boolean remove(Track track) {
			if (tracks.remove(track)) {
				if (tracks.size() == 0) this.tracks.remove(this);
				return true;
			}
			return false;
		}
		
		public boolean matches(Track track) {
			for (Track t : tracks) {
				if (t.matches(new ExtendedSearch(track.getName()))) return true;
			}
			return false;
		}
	}
	
	/***
	 * Add track to PlayList. If the track matches another track, it will be merged.
	 * @param track
	 * @return true if track was added to the list, or false if the same Track object is already in the list.
	 */
	public boolean append(Track track) {
		for (PlayListTrack t : tracks) {
			if (t.matches(track)) {
				if (t.equals(track)) return false;
				t.add(track);
				return true;
			}
		}
		tracks.add(new PlayListTrack(track));
		return false;
	}
	
	/***
	 * Remove track in position num from PlayList
	 * @param num
	 */
	public void remove(int num) {
		tracks.remove(num);
	}
	
	/***
	 * Remove all tracks from start to end (inclusive) from Playlist
	 * @param start
	 * @param end
	 */
	public void remove(int start, int end) {
		for (int i = end; i >= start; i--) {
			remove(i);
		}
	}
	
	/*public void add(int position, Track track) { 
		tracks.add(position, track);
		Callback.tracklistChanged(name);
	}*/
	
	public PlayListTrack get(int num) { return tracks.get(num); }
	
	public int size() { return tracks.size(); }
	
	/***
	 * Create a m3u playlist using the first track that has an assoiated path, and store it in outfile
	 * @param outfile
	 */
	public void writePlayListM3U(File outfile) {
		StringBuilder sb = new StringBuilder();
		sb.append("#EXTINF\n");
		for (PlayListTrack ptrack : tracks) {
			for (Track track : ptrack.tracks) {
				Addon lta = track.getAddon(LocalTrackAddon.ADDON_NAME);
				if (lta == null) continue;
				List<File> files = ((LocalTrackAddon)lta).getFile();
				if (files == null) continue;
				File file = files.get(0);
				String relative = outfile.getParentFile().toURI().relativize(file.toURI()).getPath();
				sb.append(relative + "\n");
				break;
			}
		}
		String s = new String(sb);
		System.out.println(outfile + "\n" + s);
	}
}
